package com.marketfarm.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.marketfarm.client.CachePagina.Pagina;
import com.marketfarm.client.footer.Footer;
import com.marketfarm.client.service.AbstractAsynCallback;
import com.marketfarm.client.service.CompraVendaService;
import com.marketfarm.client.service.CompraVendaServiceAsync;
import com.marketfarm.client.service.UsuarioService;
import com.marketfarm.client.service.UsuarioServiceAsync;
import com.marketfarm.shared.entity.Item;
import com.marketfarm.shared.entity.Item.TipoItem;
import com.marketfarm.shared.entity.Ordem;
import com.marketfarm.shared.entity.Ordem.TipoOrdem;
import com.marketfarm.shared.entity.Usuario;

public class Home extends Composite {

	private UsuarioServiceAsync usuarioService = GWT.create(UsuarioService.class);
	private CompraVendaServiceAsync compraVendaService = GWT.create(CompraVendaService.class);
	private Usuario usuario;
	private Map<TipoItem, Integer> itensUsuario;
	private Map<TipoItem, Item> itens;
	private TipoItem tipoItemSelecionado = TipoItem.MACA;
	private Timer atualizarAcoes;
	private Timer atualizarItens;
	private Timer atualizarUsuario;
	
	private FlowPanel flowPanel = new FlowPanel();
	private Label lblTomateTotal;
	private Label lblLimaoPreco;
	private Label lblTotal;
	private Label lblPeraAcoes;
	private Label lblLimaoTotal;
	private Label lblTomateAcoes;
	private Label lblKiwiTotal;
	private Label lblPeraPreco;
	private Label lblMacaTotal;
	private Label lblTomatePreco;
	private Label lblKiwiPreco;
	private Label lblMacaAcoes;
	private Label lblMacaPreco;
	private Label lblTotalAcoes;
	private Label lblLimaoAcoes;
	private Label lblDinheiroAcoes;
	private Label lblPeraTotal;
	private Label lblKiwiAcoes;
	private Label lblNomeUsuario;
	private CellList<TipoItem> cellListItens;
	private FlexTable tableAcoes;
	private Label lblPrecoAtual;
	private Label lblQtdDisponivel;
	
	public Home(){
		initWidget(flowPanel);
		flowPanel.setSize("", "");
		inicializar();
	}
	
	private void inicializar() {
		VerticalPanel verticalPanel = new VerticalPanel();
		verticalPanel.setSpacing(10);
		verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flowPanel.add(verticalPanel);
		verticalPanel.setSize("", "");
		
		Header header = new Header();
		verticalPanel.add(header);
		
		VerticalPanel verticalPanel1 = new VerticalPanel();
		verticalPanel.add(verticalPanel1);
		
		DecoratorPanel decoratorPanel = new DecoratorPanel();
		verticalPanel1.add(decoratorPanel);
		
		VerticalPanel verticalPanel_1 = new VerticalPanel();
		verticalPanel_1.setSpacing(10);
		decoratorPanel.setWidget(verticalPanel_1);
		verticalPanel_1.setWidth("387px");
		
		HorizontalPanel horizontalPanel_2 = new HorizontalPanel();
		verticalPanel_1.add(horizontalPanel_2);
		
		SimplePanel simplePanel = new SimplePanel();
		horizontalPanel_2.add(simplePanel);
		simplePanel.setSize("509px", "22px");
		
		HorizontalPanel horizontalPanel_1 = new HorizontalPanel();
		horizontalPanel_2.add(horizontalPanel_1);
		horizontalPanel_1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		horizontalPanel_1.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		horizontalPanel_1.setWidth("275px");
		
		Label lblBemVindo = new Label("Bem Vindo");
		lblBemVindo.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		horizontalPanel_1.add(lblBemVindo);
		lblBemVindo.setWidth("74px");
		
		lblNomeUsuario = new Label("");
		lblNomeUsuario.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		lblNomeUsuario.setStyleName("font-16");
		horizontalPanel_1.add(lblNomeUsuario);
		
		Button btnNewButton = new Button("Desconectar");
		btnNewButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				logout();
			}
		});
		horizontalPanel_1.add(btnNewButton);
		
		VerticalPanel verticalPanel_8 = new VerticalPanel();
		verticalPanel1.add(verticalPanel_8);
		
		SimplePanel simplePanel_2 = new SimplePanel();
		verticalPanel_8.add(simplePanel_2);
		simplePanel_2.setHeight("10px");
		
		HorizontalPanel horizontalPanel = new HorizontalPanel();
		verticalPanel_8.add(horizontalPanel);
		
		DecoratorPanel decoratorPanel_1 = new DecoratorPanel();
		horizontalPanel.add(decoratorPanel_1);
		
		VerticalPanel verticalPanel_2 = new VerticalPanel();
		verticalPanel_2.setSpacing(10);
		decoratorPanel_1.setWidget(verticalPanel_2);
		
		Label lblPatrimnio = new Label("Patrimônio");
		lblPatrimnio.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		lblPatrimnio.setStyleName("font-18");
		verticalPanel_2.add(lblPatrimnio);
		
		HorizontalPanel horizontalPanel_3 = new HorizontalPanel();
		verticalPanel_2.add(horizontalPanel_3);
		
		FlexTable flexTable_1 = new FlexTable();
		horizontalPanel_3.add(flexTable_1);
		
		Label lblItem = new Label("Item");
		lblItem.setStyleName("font-16");
		lblItem.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(0, 0, lblItem);
		
		Label lblAes_2 = new Label("Ações");
		lblAes_2.setStyleName("font-16");
		lblAes_2.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(0, 1, lblAes_2);
		
		Label lblPreo_4 = new Label("Preço");
		lblPreo_4.setStyleName("font-16");
		lblPreo_4.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(0, 2, lblPreo_4);
		
		Label lblNewLabel_1 = new Label("Total");
		lblNewLabel_1.setStyleName("font-16");
		lblNewLabel_1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(0, 3, lblNewLabel_1);
		
		Label lblMaas = new Label("Maçã");
		lblMaas.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(1, 0, lblMaas);
		
		lblMacaAcoes = new Label("");
		lblMacaAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(1, 1, lblMacaAcoes);
		
		lblMacaPreco = new Label("");
		lblMacaPreco.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(1, 2, lblMacaPreco);
		
		lblMacaTotal = new Label("");
		lblMacaTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(1, 3, lblMacaTotal);
		
		Label lblTomates = new Label("Tomate");
		lblTomates.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(2, 0, lblTomates);
		
		lblTomateAcoes = new Label("");
		lblTomateAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(2, 1, lblTomateAcoes);
		
		lblTomatePreco = new Label("");
		lblTomatePreco.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(2, 2, lblTomatePreco);
		
		lblTomateTotal = new Label("");
		lblTomateTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(2, 3, lblTomateTotal);
		
		Label lblSementesDeMas = new Label("Pêra");
		lblSementesDeMas.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(3, 0, lblSementesDeMas);
		
		lblPeraAcoes = new Label("");
		lblPeraAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(3, 1, lblPeraAcoes);
		
		lblPeraPreco = new Label("");
		lblPeraPreco.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(3, 2, lblPeraPreco);
		
		lblPeraTotal = new Label("");
		lblPeraTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(3, 3, lblPeraTotal);
		
		Label lblKiwi2 = new Label("Kiwi");
		lblKiwi2.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(4, 0, lblKiwi2);
		
		lblKiwiAcoes = new Label("");
		lblKiwiAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(4, 1, lblKiwiAcoes);
		
		lblKiwiPreco = new Label("");
		lblKiwiPreco.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(4, 2, lblKiwiPreco);
		
		lblKiwiTotal = new Label("");
		lblKiwiTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(4, 3, lblKiwiTotal);
		
		Label lblLimao1 = new Label("Limão");
		lblLimao1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(5, 0, lblLimao1);
		
		lblLimaoAcoes = new Label("");
		lblLimaoAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(5, 1, lblLimaoAcoes);
		
		lblLimaoPreco = new Label("");
		lblLimaoPreco.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(5, 2, lblLimaoPreco);
		
		lblLimaoTotal = new Label("");
		lblLimaoTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(5, 3, lblLimaoTotal);
		
		Label lblDinheiro1 = new Label("Dinheiro");
		lblDinheiro1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(6, 0, lblDinheiro1);
		
		lblDinheiroAcoes = new Label("");
		lblDinheiroAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(6, 3, lblDinheiroAcoes);
		
		Label lblTotal1 = new Label("Total:");
		lblTotal1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		flexTable_1.setWidget(7, 0, lblTotal1);
		lblTotal1.setStyleName("font-16");
		
		lblTotalAcoes = new Label("");
		lblTotalAcoes.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		flexTable_1.setWidget(7, 1, lblTotalAcoes);
		lblTotalAcoes.setStyleName("font-16");
		
		lblTotal = new Label("2,25");
		lblTotal.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		lblTotal.setStyleName("font-16");
		flexTable_1.setWidget(7, 3, lblTotal);
		
		SimplePanel simplePanel_3 = new SimplePanel();
		horizontalPanel.add(simplePanel_3);
		simplePanel_3.setWidth("10px");
		
		DecoratorPanel decoratorPanel_2 = new DecoratorPanel();
		horizontalPanel.add(decoratorPanel_2);
		
		VerticalPanel verticalPanel_5 = new VerticalPanel();
		verticalPanel_5.setSpacing(10);
		decoratorPanel_2.setWidget(verticalPanel_5);
		
		Label lblComprasEVendas = new Label("Compras e Vendas");
		lblComprasEVendas.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		lblComprasEVendas.setStyleName("font-18");
		verticalPanel_5.add(lblComprasEVendas);
		
		HorizontalPanel horizontalPanel_4 = new HorizontalPanel();
		verticalPanel_5.add(horizontalPanel_4);
		
		cellListItens = new CellList<TipoItem>(new AbstractCell<TipoItem>(){
			
			@Override
			public void render(Context context, TipoItem ti, SafeHtmlBuilder sb) {
				sb.appendHtmlConstant("<table width='80px'><tr><td>");

				sb.appendHtmlConstant("<img src='imgs/" + ti.toString() + ".png'/>");
				
				sb.appendHtmlConstant("</td>");

				sb.appendHtmlConstant("<td>");
				sb.appendHtmlConstant(itens.get(ti).getNome());
				sb.appendHtmlConstant(" (");
				sb.appendHtmlConstant(itens.get(ti).getValor().toString());
				sb.appendHtmlConstant(")</td></tr></table>");
			}
		});
		horizontalPanel_4.add(cellListItens);

		final SingleSelectionModel<TipoItem> selectionModel = new SingleSelectionModel<TipoItem>();
		cellListItens.setSelectionModel(selectionModel);
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {
				tipoItemSelecionado = selectionModel.getSelectedObject();
				
				int rows = tableAcoes.getRowCount();
				while(--rows >= 2) tableAcoes.removeRow(rows);
				
				if(atualizarAcoes != null){
					atualizarAcoes.cancel();
					atualizarAcoes();
				}
			}
		});
		selectionModel.setSelected(TipoItem.MACA, true);
		
		HorizontalPanel horizontalPanel_5 = new HorizontalPanel();
		horizontalPanel_5.setStyleName("backGroundGray");
		horizontalPanel_4.add(horizontalPanel_5);
		
		VerticalPanel verticalPanel_6 = new VerticalPanel();
		horizontalPanel_5.add(verticalPanel_6);
		
		lblPrecoAtual = new Label("2,30");
		lblPrecoAtual.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		lblPrecoAtual.setStyleName("font-16");
		verticalPanel_6.add(lblPrecoAtual);
		
		VerticalPanel verticalPanel_7 = new VerticalPanel();
		verticalPanel_7.setBorderWidth(0);
		verticalPanel_6.add(verticalPanel_7);
		
		tableAcoes = new FlexTable(){
			@Override
			public CellFormatter getCellFormatter() {
				return new FlexTable.FlexCellFormatter(){
					@Override
					public String getStyleName(int row, int column) {
						return row % 2 == 0 ? "font-18" : null;
					}
				};
			}
		};
		tableAcoes.setBorderWidth(0);
		verticalPanel_7.add(tableAcoes);
		
		Label lblCompras = new Label("Compras");
		lblCompras.setStyleName("font-16");
		lblCompras.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(0, 0, lblCompras);
		tableAcoes.getFlexCellFormatter().setColSpan(0, 0, 2);
		tableAcoes.getFlexCellFormatter().setColSpan(0, 1, 1);
		
		Label lblVendas = new Label("Vendas");
		lblVendas.setStyleName("font-16");
		lblVendas.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(0, 1, lblVendas);
		
		Label lblQtd = new Label("Qtd");
		lblQtd.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(1, 0, lblQtd);
		tableAcoes.getCellFormatter().setWidth(1, 0, "44px");
		
		Label lblPreo = new Label("Preço");
		lblPreo.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(1, 1, lblPreo);
		tableAcoes.getCellFormatter().setWidth(1, 1, "44px");
		
		Label lblQuantidade = new Label("Qtd");
		lblQuantidade.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(1, 2, lblQuantidade);
		tableAcoes.getCellFormatter().setWidth(1, 2, "44px");
		
		Label lblPreo_1 = new Label("Preço");
		lblPreo_1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		tableAcoes.setWidget(1, 3, lblPreo_1);
		tableAcoes.getCellFormatter().setWidth(1, 3, "44px");
		tableAcoes.getFlexCellFormatter().setColSpan(0, 1, 2);
		
		VerticalPanel verticalPanel_3 = new VerticalPanel();
		verticalPanel_3.setSpacing(5);
		horizontalPanel_5.add(verticalPanel_3);
		
		DecoratorPanel decoratorPanel_3 = new DecoratorPanel();
		verticalPanel_3.add(decoratorPanel_3);
		
		FlexTable flexTable_2 = new FlexTable();
		decoratorPanel_3.setWidget(flexTable_2);
		
		HorizontalPanel horizontalPanel_6 = new HorizontalPanel();
		flexTable_2.setWidget(0, 0, horizontalPanel_6);
		
		Label lblAesDisponveis = new Label("Quantidade Disponível: ");
		horizontalPanel_6.add(lblAesDisponveis);
		lblAesDisponveis.setStyleName("font-16");
		
		lblQtdDisponivel = new Label("9");
		horizontalPanel_6.add(lblQtdDisponivel);
		lblQtdDisponivel.setStyleName("font-16");
		
		final Button btnVender = new Button("Vender");
		flexTable_2.setWidget(1, 4, btnVender);
		btnVender.setWidth("64px");
		
		final TextBox tbVlrVenda = new TextBox();
		tbVlrVenda.setVisibleLength(1);
		flexTable_2.setWidget(1, 3, tbVlrVenda);
		
		Label lblPreo_2 = new Label("Preço:");
		flexTable_2.setWidget(1, 2, lblPreo_2);
				
		final TextBox tbQtdVenda = new TextBox();
		tbQtdVenda.setVisibleLength(1);
		flexTable_2.setWidget(1, 1, tbQtdVenda);
		
		Label lblAes = new Label("Qtd:");
		flexTable_2.setWidget(1, 0, lblAes);
		flexTable_2.getCellFormatter().setWidth(1, 0, "42px");
		
		final Button btnComprar = new Button("Comprar");
		flexTable_2.setWidget(2, 4, btnComprar);
		btnComprar.setWidth("64px");
		
		final TextBox tbVlrCompra = new TextBox();
		tbVlrCompra.setVisibleLength(1);
		flexTable_2.setWidget(2, 3, tbVlrCompra);
		
		Label lblPreo_3 = new Label("Preço");
		flexTable_2.setWidget(2, 2, lblPreo_3);
		
		Label lblAes_1 = new Label("Qtd:");
		flexTable_2.setWidget(2, 0, lblAes_1);
		
		final TextBox tbQtdCompra = new TextBox();
		tbQtdCompra.setVisibleLength(1);
		flexTable_2.setWidget(2, 1, tbQtdCompra);
		flexTable_2.getFlexCellFormatter().setColSpan(0, 0, 5);
		flexTable_2.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);

		btnVender.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Integer qtd = 0;
				Double vlr = 0D;
				
				try{
					qtd = Integer.valueOf(tbQtdVenda.getText());
					vlr = Double.valueOf(tbVlrVenda.getText());
				}catch(Exception e){}
				
				final Integer qtdFinal = qtd;
				
				if(tbQtdVenda.getText().isEmpty() || tbVlrVenda.getText().isEmpty()){
					Window.alert("Preencha o campo quantidade e preço");
					return;
				}
				if(qtd == 0 || vlr == 0){
					Window.alert("Os campos quantidade e preço devem ser maior que zero");
					return;
				}
				
				btnComprar.setEnabled(false);
				btnVender.setEnabled(false);
				
				String sessao = Cookies.getCookie("sid");  
				
				compraVendaService.vender(sessao, tipoItemSelecionado, qtd, vlr, new AbstractAsynCallback<Ordem>(){
					@Override
					public void onSuccess(Ordem result) {
						if(result == null) Window.alert("Venda executada com sucesso");
						else Window.alert("Você vendeu " + (qtdFinal - result.getQuantidade()) + " ações e o restante foi adicionado a listagem");
						
						btnComprar.setEnabled(true);
						btnVender.setEnabled(true);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						btnComprar.setEnabled(true);
						btnVender.setEnabled(true);
						
						super.onFailure(caught);
					}
				});
			}
		});
		
		btnComprar.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Integer qtd = 0;
				Double vlr = 0D;
				
				try{
					qtd = Integer.valueOf(tbQtdCompra.getText());
					vlr = Double.valueOf(tbVlrCompra.getText());
				}catch(Exception e){}
				
				final Integer qtdFinal = qtd;
				
				if(tbQtdCompra.getText().isEmpty() || tbVlrCompra.getText().isEmpty()){
					Window.alert("Preencha o campo quantidade e preço");
					return;
				}
				if(qtd == 0 || vlr == 0){
					Window.alert("Os campos quantidade e preço devem ser maior que zero");
					return;
				}
				
				btnComprar.setEnabled(false);
				btnVender.setEnabled(false);
				
				String sessao = Cookies.getCookie("sid");  
				
				compraVendaService.comprar(sessao, tipoItemSelecionado, qtd, vlr, new AbstractAsynCallback<Ordem>(){
					@Override
					public void onSuccess(Ordem result) {
						if(result == null) Window.alert("Compra executada com sucesso");
						else Window.alert("Você comprou " + (qtdFinal - result.getQuantidade()) + " ações e o restante foi adicionado a listagem");
						
						btnComprar.setEnabled(true);
						btnVender.setEnabled(true);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						btnComprar.setEnabled(true);
						btnVender.setEnabled(true);
						
						super.onFailure(caught);
					}
				});
			}
		});
		
		Footer footer = new Footer();
		verticalPanel.add(footer);
		
		atualizarDados();
	}
	
	private void atualizarDados(){
		compraVendaService.getItens(new Date().getTime(), new AbstractAsynCallback<Map<TipoItem,Item>>(){
			@Override
			public void onSuccess(Map<TipoItem, Item> result) {
				itens = result;
				atualizarUsuario();
				atualizarAcoes();
				atualizarItens();
			}
		});
		
		String sessao = Cookies.getCookie("sid");
		usuarioService.getUsuario(sessao, new Date().getTime(), new AbstractAsynCallback<Usuario>(){
			@Override
			public void onSuccess(Usuario result) {
				usuario = result;
				lblNomeUsuario.setText(usuario.getNick());
			}
		});
	}
	
	private void atualizarAcoes(){
		compraVendaService.getOrdensAtuais(tipoItemSelecionado, new Date().getTime(), new AbstractAsynCallback<Map<TipoOrdem, List<Ordem>>>(){
			@Override
			public void onSuccess(Map<TipoOrdem, List<Ordem>> result) {
				lblPrecoAtual.setText(itens.get(tipoItemSelecionado).getValor() + "");
				
				List<Ordem> compras = result.get(TipoOrdem.COMPRA);
				List<Ordem> vendas = result.get(TipoOrdem.VENDA);
				
				if(compras != null){
					int row = 2;
					for (Ordem ordem : compras) {
						Label l = new Label(ordem.getQuantidade() + "");
						l.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						tableAcoes.setWidget(row, 0, l);
						
						l = new Label(ordem.getPreco() + "");
						l.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						tableAcoes.setWidget(row, 1, l);
						
						row++;
					}
				}
				
				if(vendas != null){
					int row = 2;				
					for (Ordem ordem : vendas) {
						Label l = new Label(ordem.getQuantidade() + "");
						l.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						tableAcoes.setWidget(row, 2, l);
						
						l = new Label(ordem.getPreco() + "");
						l.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						tableAcoes.setWidget(row, 3, l);
						
						row++;
					}
				}
				
				atualizarAcoes = new Timer() {
					@Override
					public void run() {
						atualizarAcoes();
					}
				};
				atualizarAcoes.schedule(2000);
			}
		});
	}
	
	private void atualizarItens(){
		compraVendaService.getItens(new Date().getTime(), new AbstractAsynCallback<Map<TipoItem,Item>>(){
			@Override
			public void onSuccess(Map<TipoItem, Item> result) {
				itens = result;
				cellListItens.setRowData(Arrays.asList(TipoItem.values()));
				cellListItens.setTabIndex(3);
				
				atualizarItens = new Timer() {
					@Override
					public void run() {
						atualizarItens();
					}
				};
				atualizarItens.schedule(2000);
			}
		});
	}
	
	private void atualizarUsuario(){
		String sessao = Cookies.getCookie("sid");
		usuarioService.getUsuario(sessao, new Date().getTime(), new AbstractAsynCallback<Usuario>(){
			@Override
			public void onSuccess(Usuario result) {
				usuario = result;
				itensUsuario = usuario.getQuantidadeItem();
				Integer itensAVenda = usuario.getQuantidadeItemAVenda().get(tipoItemSelecionado);
				lblQtdDisponivel.setText((itensUsuario.get(tipoItemSelecionado) - itensAVenda) + "");
				
				atualizarPatrimonio();
				
				atualizarUsuario = new Timer() {
					@Override
					public void run() {
						atualizarUsuario();
					}
				};
				atualizarUsuario.schedule(2000);
			}
		});
	}

	private void atualizarPatrimonio(){
		Integer qtdMaca = itensUsuario.get(TipoItem.MACA);
		Double vlrMaca = itens.get(TipoItem.MACA).getValor();
		lblMacaAcoes.setText(qtdMaca.toString());
		lblMacaPreco.setText(vlrMaca.toString());
		lblMacaTotal.setText((qtdMaca * vlrMaca) + "");

		Integer qtdTomate = itensUsuario.get(TipoItem.TOMATE);
		Double vlrTomate = itens.get(TipoItem.TOMATE).getValor();
		lblTomateAcoes.setText(qtdTomate.toString());
		lblTomatePreco.setText(vlrTomate.toString());
		lblTomateTotal.setText((qtdTomate * vlrTomate) + "");

		Integer qtdPera = itensUsuario.get(TipoItem.PERA);
		Double vlrPera = itens.get(TipoItem.PERA).getValor();
		lblPeraAcoes.setText(qtdPera.toString());
		lblPeraPreco.setText(vlrPera.toString());
		lblPeraTotal.setText((qtdPera * vlrPera) + "");

		Integer qtdKiwi = itensUsuario.get(TipoItem.KIWI);
		Double vlrKiwi = itens.get(TipoItem.KIWI).getValor();
		lblKiwiAcoes.setText(qtdKiwi.toString());
		lblKiwiPreco.setText(vlrKiwi.toString());
		lblKiwiTotal.setText((qtdKiwi * vlrKiwi) + "");

		Integer qtdLimao = itensUsuario.get(TipoItem.LIMAO);
		Double vlrLimao = itens.get(TipoItem.LIMAO).getValor();
		lblLimaoAcoes.setText(qtdLimao.toString());
		lblLimaoPreco.setText(vlrLimao.toString());
		lblLimaoTotal.setText((qtdLimao * vlrLimao) + "");

		Double qtdDinheiro = usuario.getDinheiro();
		lblDinheiroAcoes.setText(qtdDinheiro.toString());

		lblTotalAcoes.setText((qtdLimao + qtdKiwi + qtdMaca + qtdPera + qtdTomate) + "");
		lblTotal.setText(((qtdMaca * vlrMaca + qtdTomate * vlrTomate + qtdPera * vlrPera +
				qtdKiwi * vlrKiwi + qtdLimao * vlrLimao) + qtdDinheiro) + "");
	}
	
	private void logout(){
		usuarioService.logout(new AbstractAsynCallback<Void>(){
			@Override
			public void onSuccess(Void result) {
				atualizarAcoes.cancel();
				atualizarItens.cancel();
				atualizarUsuario.cancel();
				
				CachePagina.getInstance().apagarPagina(Pagina.HOME);
				
				Cookies.removeCookie("sid");
				History.newItem(Pagina.LOGIN.toString());
			}
		});
	}
}
